package www.woniuxy.com.class112.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.core.convert.converter.Converter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import www.woniuxy.com.class112.interceptor.LoginInterceptor;
import www.woniuxy.com.class112.interceptor.PermissionInterceptor;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Resource
    private LoginInterceptor loginInterceptor;
    @Resource
    private PermissionInterceptor permissionInterceptor;
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 所有接口
                .allowCredentials(true) // 是否发送 Cookie
                .allowedOrigins("*") // 支持域
                .allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"})
                .allowedHeaders("*")
                .exposedHeaders("*");
    }
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //注册登录拦截器
        registry.addInterceptor(loginInterceptor).
                addPathPatterns("/**")
                .excludePathPatterns("/userInfo/userLogin","/userInfo/agentLogin","/userInfo/adminRegistration","/userInfo/LoginVerificationCode","/userInfo/loginWithPhoneNumber","/userInfo/adminLogin")//"/userInfo/adminLogin",,"/userInfo/sendRegisterCode"
                .excludePathPatterns("/userInfo/registrationVerificationCode","/userInfo/userMobileNumberRegistration")
                .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");
        //注册权限拦截器
        registry.addInterceptor(permissionInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/userInfo/userLogin","/userInfo/agentLogin","/userInfo/adminRegistration","/userInfo/LoginVerificationCode","/userInfo/loginWithPhoneNumber")//"/userInfo/adminLogin",,"/userInfo/sendRegisterCode"
                .excludePathPatterns("/userInfo/registrationVerificationCode","/userInfo/userMobileNumberRegistration")
                .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");

    }
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new Converter<String, LocalDate>() {

            @Override
            public LocalDate convert(String source) {
                return LocalDate.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            }
        });
    }


}
